package com.lmk.mkcc.mq.consumer;

import com.lmk.mkcc.domain.PayOrder;
import com.lmk.mkcc.enums.GlobalErrorCode;
import com.lmk.mkcc.service.IPayOrderService;
import com.lmk.mkcc.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = "overtime-delayed-group",
        topic = "overtime-delayed-topic",
        selectorExpression = "overtime-delayed-tag",
        messageModel = MessageModel.BROADCASTING
)
public class CourseOrderDelayedConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IPayOrderService payOrderService;
    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        String orderNo = new String(body, StandardCharsets.UTF_8);
        AssertUtil.isNotNull(orderNo, GlobalErrorCode.SERVICE_PARAM_IS_NULL);
        PayOrder byOrderNo = payOrderService.getByOrderNo(orderNo);
        if (byOrderNo==null){
            return;
        }
        if (PayOrder.WAIT_PAY.equals(byOrderNo.getPayStatus())){
            try {
                payOrderService.cancelOrder(orderNo, byOrderNo);
            } catch (Exception e) {
                log.error("订单关闭失败，订单号为：{}", orderNo);
                e.printStackTrace();
            }
        }
    }
}
